package io.mft.commons.db.mapper.transaction;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.Session;
import io.mft.commons.db.mapper.builder.ParameterWrapper;
import io.mft.commons.db.mapper.exception.MapperException;
import io.mft.commons.db.mapper.transaction.impl.MapperTransactionImpl;
import io.mft.commons.db.source.DbProvider;
/**
 * Mapper事务工厂
 * @类型名称：MapperTransactionFactory
 * @说明：TODO
 * @创建者: 胡常建  
 * @创建时间: 2018年4月20日 上午9:56:25
 * @修改者: 胡常建  
 * @修改时间: 2018年4月20日 上午9:56:25
 */
public class MapperTransactionFactory {

	private static final MapperTransactionFactory instance=new MapperTransactionFactory();
	private final ThreadLocal<MapperTransaction> threadLocal=new ThreadLocal<MapperTransaction>();
	public static MapperTransactionFactory getInstance() {
		return instance;
	}
	private MapperTransactionFactory() {}
	public MapperTransaction build() {
		MapperTransaction transaction=new MapperTransactionImpl(threadLocal);
		threadLocal.set(transaction);
		return transaction;
	}
	public MapperTransaction getThreadMapperTransaction() {
		MapperTransaction transaction=threadLocal.get();
		return transaction;
	}
	private static String parseDatasourceId(ParameterWrapper parameterWrapper) {
		String datasourceId="";
		if (parameterWrapper.getDatasourceWraper()!=null&&!ObjectUtil.isEmpty(parameterWrapper.getDatasourceWraper().getId())) {
			datasourceId=parameterWrapper.getDatasourceWraper().getId();
		}
		if (ObjectUtil.isEmpty(datasourceId)) {
			datasourceId=parameterWrapper.getParameterMetadataWrapper().getDatasourceId();
		}
		return datasourceId;
	}
	public MapperDbOperator buildMapperDbOperator(ParameterWrapper parameterWrapper) {
		try {
			MapperTransaction transaction=getThreadMapperTransaction();
			boolean auto=false;
			if (transaction==null) {
				transaction=build();
				auto=true;
			}
			String datasourceId=parseDatasourceId(parameterWrapper);
			Session session=transaction.getSession(datasourceId);
			if (session==null) {
				session = DbProvider.getInstance().getSession(datasourceId);
			}
			MapperDbOperator dbOperator=new MapperDbOperator((MapperTransactionImpl)transaction,session,datasourceId,auto);
			return dbOperator;
		} catch (Exception e) {
			throw new MapperException("构造数据库操作对象异常", e);
		}
	}
	

}
